package com.syher.quartz.core.config.pool;

import com.syher.quartz.core.config.pool.monitor.ThreadPoolMonitor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by shenyuhang on 2018/3/7.
 */
@Configuration
public class ThreadPoolConfiguration {

    @Autowired
    private ThreadPoolProperties prop;

    @Bean(name="poolExecutor")
    public ThreadPoolExecutor registerPoolExecutor() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(prop.getCorePoolSize(),
                prop.getMaxPoolSize(),
                prop.getKeepAliveSeconds(),
                TimeUnit.SECONDS,
                new LinkedBlockingQueue(prop.getQueueCapacity()),
                getTaskRejectedHandler());

        return executor;
    }

    private ThreadPoolRejectedExecutionHandler getTaskRejectedHandler() {
        return new ThreadPoolRejectedExecutionHandler();
    }

    @Bean
    public ThreadPoolMonitor registerPoolMonitor(@Qualifier("poolExecutor")ThreadPoolExecutor executor) {
        ThreadPoolMonitor monitor = new ThreadPoolMonitor();
        monitor.setPeriod(5);
        monitor.setExecutor(executor);
        return monitor;
    }

}
